package com.example.lib_base

import androidx.lifecycle.ViewModel
import com.example.lib_base.state.RealContainer
import com.example.lib_base.state.UiState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart

abstract class BaseViewModel<RESP:BaseRepository,STATE:UiState>:ViewModel() {

    lateinit var resp:RESP
    var state:STATE=createState()
    private var _mutableContainer=RealContainer(state)
    var mutableContainer=_mutableContainer

    abstract fun createState(): STATE
    abstract fun createResp(): RESP

    init {
        resp=createResp()
    }

    fun comFlow(flow: Flow<BaseEntity>):Flow<BaseEntity>{
        return flow.flowOn(Dispatchers.IO)
            .catch {
                it.printStackTrace()
            }
            .onStart {
                mutableContainer.updateRequestState { copy(request=true,complete = false) }
            }.onCompletion {
                mutableContainer.updateRequestState { copy(request=false,complete = true) }
            }
    }
}